<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createPayment, getOrderDetail } from '../../api/order'

const route = useRoute()
const router = useRouter()

const order = ref({
  id: route.params.orderId,
  orderNo: '',
  orderName: '',
  price: 0
})

const paymentMethod = ref(1)
const loading = ref(false)

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    const response = await getOrderDetail(route.params.orderId)
    order.value = response.data
  } catch (error) {
    ElMessage.error('获取订单信息失败')
    router.go(-1)
  }
}

onMounted(() => {
  fetchOrderDetail()
})

const handleSubmit = async () => {
  try {
    loading.value = true
    const response = await createPayment({
      orderId: order.value.id,
      orderNo: order.value.orderNo,
      paymentMethod: paymentMethod.value,
      amount: order.value.price,
      subject: order.value.orderName,
      body: '酒店房间预订',
      clientIp: '127.0.0.1'
    })

    if (response.data.payUrl) {
      // 跳转到支付页面
      window.location.href = response.data.payUrl
    } else {
      // 支付成功，跳转到支付结果页面
      router.push({
        name: 'payment-result',
        params: { paymentNo: response.data.paymentNo }
      })
    }
  } catch (error) {
    ElMessage.error(error.message || '支付创建失败')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  router.go(-1)
}
</script>

<template>
  <div class="payment-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>订单支付</h3>
        </div>
      </template>

      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ order.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单名称">{{ order.orderName }}</el-descriptions-item>
        <el-descriptions-item label="支付金额">
          <span class="price">¥{{ order.price.toFixed(2) }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider />

      <h4>选择支付方式</h4>
      <el-radio-group v-model="paymentMethod">
        <el-radio :label="1">支付宝</el-radio>
        <el-radio :label="2">微信支付</el-radio>
        <el-radio :label="3">银行卡</el-radio>
      </el-radio-group>

      <div class="actions">
        <el-button type="primary" @click="handleSubmit" :loading="loading">立即支付</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.payment-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}
.actions {
  margin-top: 30px;
  text-align: center;
}
</style>